import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Between, Like, Repository } from 'typeorm';
import { MongodbService } from '~/shared/mongodb/mongodb.service';
import { paginate, Pagination, paginateAggregate } from '~/helper/paginate';
import { BusinessException } from '~/common/exceptions/business.exception';
import { ErrorEnum } from '~/constants/error-code.constant';
import { deleteFile } from '~/utils';
import { Storage } from '~/shared/mongodb/schema/storage.schema';
import { QueryProductDto, DeleteStorageDto } from './storage.dto';

@Injectable()
export class StorageService {
  constructor(private readonly mongodbService: MongodbService) {}

  /**
   * 删除文件
   */
  async delete(fileIds: number[]): Promise<void> {
    //查询要删除的文件
    const items = await this.mongodbService.StorageModel.find({
      _id: { $in: fileIds },
    }).exec();
    if (!items.length) {
      throw new BusinessException(ErrorEnum.INVALID_FILE);
    }
    await this.mongodbService.StorageModel.deleteMany({
      _id: { $in: fileIds },
    }).exec();

    items.forEach(el => {
      deleteFile(el.path);
    });
  }

  async list({
    page,
    pageSize,
    name,
    type,
    size,
    extName,
    time,
  }: QueryProductDto) {
    // 构建查询条件
    const query: any = {};

    if (name) {
      query.name = { $regex: name, $options: 'i' }; // 不区分大小写的模糊查询
    }

    if (type) {
      query.type = type;
    }

    if (extName) {
      query.extName = extName;
    }

    if (size && size.length === 2) {
      query.size = { $gte: size[0], $lte: size[1] };
    }

    if (time && time.length === 2) {
      query.createdAt = { $gte: time[0], $lte: time[1] };
    }

    return paginate(
      this.mongodbService.StorageModel,
      { page: page, pageSize: pageSize },
      query,
    );
  }
}
